<template>
<view class="container">
  <view class="studentlayout">
    <!-- 学生信息 -->
    <view class="student-info">
      <view class="avatar-image" @click="gotostudentInfo">
        <image class="avatar" :src="imagePath" mode="aspectFill"></image>
      </view>
      <view class="user-info">
        <view class="username">{{userInfo.name}}</view>
        <view class="slogan">学号: {{userInfo.studentId}}</view>
      </view>
    </view>

    <view class="course-container">
      <view class="course-item" @click="openJoinDialog">
        <text class="cuIcon cuIcon-roundadd"></text>
        <view>加入班级</view>
      </view>
      <view class="course-item" @click="gototimeable">
        <text class="cuIcon cuIcon-read"></text>
        <view>课程表</view>
      </view>
    </view>

    <!-- 加入班级弹窗 -->
    <popup :show="showJoinDialog" @close="closeJoinDialog" @confirm="handleJoinClass" title="加入班级">
      <input 
        class="class-input"
        type="text" 
        placeholder="请输入班级ID" 
        v-model="classId"
      />
    </popup>

    <!-- 班级列表 -->
    <view class="class-info">
      <view class="class-detail" v-for="item in classlist" :key="item.id">
        <text>{{ item.className }}</text>
        <view class="class-meta">
          <text>班主任: {{ item.teacherName }}</text>
          <text>状态: {{ item.status | statusText }}</text>
        </view>
      </view>
    </view>

    <!-- 课程表展示 -->
    <view class="course-list" v-if="courseList.length">
      <view class="course-card" v-for="(course, index) in courseList" :key="index">
        <text>{{ course.courseName }}</text>
        <view class="course-info">
          <text>时间: {{ course.day }} {{ course.time }}</text>
          <text>地点: {{ course.location }}</text>
        </view>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <view class="tab-bar">
      <view 
        class="tab-item" 
        :class="{active: currentTab === 0}" 
        @click="switchTab(0)"
      >
        <text class="cuIcon cuIcon-home"></text>
        <text class="tab-text">首页</text>
      </view>
      
      <view 
        class="tab-item" 
        :class="{active: currentTab === 1}" 
        @click="switchTab(1)"
      >
        <text class="cuIcon cuIcon-form"></text>
        <text class="tab-text">申请</text>
      </view>
      
      <view 
        class="tab-item" 
        :class="{active: currentTab === 2}" 
        @click="switchTab(2)"
      >
        <text class="cuIcon cuIcon-message"></text>
        <text class="tab-text">消息</text>
      </view>
      
      <view 
        class="tab-item" 
        :class="{active: currentTab === 3}" 
        @click="switchTab(3)"
      >
        <text class="cuIcon cuIcon-my"></text>
        <text class="tab-text">我的</text>
      </view>
    </view>
  </view>
  </view>
</template>

<script>
import popup from '@/components/popup/popup.vue'

export default {
  components: { popup },
  data() {
    return {
      currentTab: 0,
      imagePath: uni.getStorageSync('studentAvatar') || require('@/static/images/avatar.png'),
      userInfo: {},
      showJoinDialog: false,
      classId: '',
      classlist: [],
      courseList: [],
      isLoading: false,
      classlist: uni.getStorageSync('studentClass') || [
        {
          id: 'C2023001',
          className: '23人工智能C班',
          teacherName: '李老师',
          status: 0,
          students: 35
        }
      ]
    }
  },
  filters: {
    statusText(status) {
      return status === 0 ? '正常' : '已禁用'
    }
  },
  onShow() {
    this.checkLoginStatus()
    this.loadClasses()
  },
  methods: {
    checkLoginStatus() {
      const userInfo = uni.getStorageSync('userInfo')
      if (!userInfo) {
        uni.redirectTo({ url: '/pages/login/login' })
        return
      }
      this.userInfo = {
        name: userInfo.name,
        studentId: userInfo.id || 'S202300001',
        role: userInfo.roleName
      }
    },
    async loadClasses() {
      try {
        const { code, data } = await getStudentClasses(this.userInfo.studentId)
        if (code === 200) {
          this.classlist = data.map(cls => ({
            ...cls,
            className: cls.className || '未知班级',
            teacherName: cls.teacherName || '未分配班主任'
          }))
          uni.setStorageSync('studentClass', this.classlist)
        }
      } catch (error) {
        uni.showToast({ title: '加载班级失败', icon: 'none' })
      }
    },
    async handleJoinClass() {
      if (!this.classId.trim()) {
        return uni.showToast({ title: '请输入班级ID', icon: 'none' })
      }
      if (this.isLoading) return
      
      this.isLoading = true
      
      await new Promise(resolve => setTimeout(resolve, 800))
      
      try {
        const success = Math.random() > 0.2
        
        if (success) {
          const mockClass = {
            id: `C${Date.now()}`,
            className: `模拟班级-${this.classId}`,
            teacherName: '模拟班主任',
            status: 0,
            students: Math.floor(Math.random() * 50) + 30
          }
          
          this.classlist = [mockClass, ...this.classlist]
          uni.setStorageSync('studentClass', this.classlist)
          
          uni.showToast({ title: '加入成功' })
          this.closeJoinDialog()
        } else {
          throw new Error(Math.random() > 0.5 ? '班级不存在' : '已加入该班级')
        }
      } catch (error) {
        uni.showToast({ title: error.message, icon: 'none' })
      } finally {
        this.isLoading = false
      }
    },
    async loadCourseTable(classId) {
      try {
        const { code, data } = await getcourselist(classId)
        if (code === 200) {
          this.courseList = data.map(item => ({
            ...item,
            location: this.parseLocation(item.courseName)
          }))
          uni.setStorageSync('courseList', this.courseList)
        }
      } catch (error) {
        uni.showToast({ title: '获取课表失败', icon: 'none' })
      }
    },
    parseLocation(courseName) {
      const regex = /（([^）]+)）/
      const match = courseName.match(regex)
      return match ? match[1] : '地点未指定'
    },
    gototimeable() {
      if (this.classlist.length === 0) {
        return uni.showToast({ title: '请先加入班级', icon: 'none' })
      }
      uni.navigateTo({
          url: `/pages/timeable/timeable?classId=${this.classlist[0].id}`
        })
    },
    openJoinDialog() {
      this.showJoinDialog = true
    },
    closeJoinDialog() {
      this.showJoinDialog = false
      this.classId = ''
    },
    gotostudentInfo() {
      uni.navigateTo({
        url: `/pages/studentInfo/studentInfo?studentId=${this.userInfo.studentId}`
      })
    },
    switchTab(index) {
      
      const routes = [
        '/pages/student/student',
        '/pages/application/list',
        '/pages/notification/list',
        '/pages/user/profile'
      ];
      
      if (index >= routes.length) {
        uni.showToast({
          title: '功能正在开发中',
          icon: 'none'
        });
        return;
      }
      
      uni.navigateTo({
            url: routes[index],
            success: () => {
              console.log('路由跳转成功:', routes[index]);
            },
            fail: (err) => {
              console.error('路由跳转失败:', err);
              uni.showToast({
                title: '页面加载失败',
                icon: 'none'
              });
            }
          });
    }
  }
}
</script>

<style>
@import url("css/student.css");
@import url("../../components/watch-login/css/icon.css");
</style>
